package com.sf.membernew.controller.waybill;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.sf.common.vo.ResultVo;
import com.sf.member.config.LogAppender;
import com.sf.member.context.BlackKeywordInterceptor;
import com.sf.member.dto.user.UserLocaleInfo;
import com.sf.member.entity.addrbook.UCMPPage;
import com.sf.member.entity.ticket.TicketConstant;
import com.sf.member.securitylog.LoggerByLevel;
import com.sf.member.service.order.IOrderService;
import com.sf.member.util.Common;
import com.sf.member.util.StringUtils;
import com.sf.member.util.SystemContants;
import com.sf.member.vo.order.OrderVo;
import com.sf.member.vo.order.UpdateOrdersVO;
import com.sf.member.webservice.util.WebServiceUtil;
import com.sf.membernew.context.UserSession;
import com.sf.membernew.controller.BaseNewController;
import com.sf.membernew.entity.Page;
import com.sf.membernew.service.order.IMyOrderNewService;
import com.sf.membernew.service.order.IOrderNewService;
import com.sf.membernew.service.order.OrderServiceHandler;
import com.sf.membernew.service.waybill.IWaybillNewService;
import com.sf.membernew.vo.order.OrderRecAddressVo;
import com.sf.membernew.vo.order.OrderRecPropsVo;
import com.sf.membernew.vo.order.OrderRecVo;
import com.sf.membernew.vo.order.OrderSenderVo;
import com.sf.membernew.vo.ucmp.ResultUCMPVo;
import com.sf.membernew.vo.waybill.OrderExportDataVo;
import com.sf.membernew.vo.waybill.OrderExportExcelView;
import com.sf.membernew.vo.waybill.UCMPResultVo;
import com.sf.membernew.vo.waybill.VagueMemBillOrderParamVo;
import com.sf.membernew.vo.waybill.WaybillNewVO;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author sfit0035
 * @date 2013-6-13 描述：收、寄运单查询
 */
@Controller
@SessionAttributes({ TicketConstant.SESSION_KEY.TLS_MEM_NO })
public class NewWayBillQueryController extends BaseNewController {
	private static final String MEM_NO = "memNo";

	private static final String PARAM_NULL = "param_null";

	private static final Logger LOG = Logger.getLogger(LogAppender.WAYBILL);

	@Autowired
	private IWaybillNewService wayBillNewService;
	@Autowired
	private IOrderService orderService;
	@Autowired
	private IMyOrderNewService myOrderNewService;
	@Autowired
	private IOrderNewService orderNewService;
	@Autowired
	private OrderServiceHandler orderServiceHandler;

	/**
	 * 个人版导出运单前查询运单数量
	 * 
	 * @param paramVo
	 * @param memNo
	 *            会员号
	 * @return
	 */
	@RequestMapping(value = "/{areaCode}/{lanCode}/waybill/export/rows", method = RequestMethod.GET)
	@ResponseBody
	public Object queryDataRows(VagueMemBillOrderParamVo paramVo, @ModelAttribute(TicketConstant.SESSION_KEY.TLS_MEM_NO) String memNo) {
		String exportSwitch = WebServiceUtil.getPropertiesConfig("exportAllWaybillSwitch");
		if ("0".equals(exportSwitch)) {
			return ResultVo.error("SWITCH_STOP", "导出功能已暂停使用！");
		}
		paramVo.setMemNo(memNo);
		paramVo.getPage().setPageSize("1");
		String inputString = JSON.toJSONString(paramVo, true);
		LOG.info("UCMP接口VagueMemBillOrder输入参数：" + inputString);
		try {
			String jsonString = orderService.vagueMemBillOrder(inputString);
			UCMPResultVo resultVo = JSON.parseObject(jsonString, UCMPResultVo.class);
			JSONObject object = JSONObject.fromObject(resultVo.getResult());
			String pageString = object.getString("page");
			UCMPPage page = JSON.parseObject(pageString, UCMPPage.class);
			LOG.info("UCMP返回的分页数据：" + JSON.toJSONString(page, true));
			int total = page != null ? page.getTotalCount() : 0;
			String limitString = WebServiceUtil.getPropertiesConfig("EXP_WAYBILL_MAX_COUNT");
			int limit = NumberUtils.isNumber(limitString) ? Integer.valueOf(limitString) : 0;
			if (total > limit) {
				return ResultVo.error("TOO_MUCH", String.valueOf(limit));
			}
			return ResultVo.success(total);
		} catch (Exception e) {
			LOG.error("查询运单数量异常：", e);
			return ResultVo.error("ERROR", e.getMessage());
		}
	}

	/**
	 * 个人版导出运单
	 * 
	 * @param paramVo
	 * @param memNo
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/{areaCode}/{lanCode}/waybill/order/export", method = RequestMethod.GET)
	public ModelAndView exportOrder(VagueMemBillOrderParamVo paramVo, @ModelAttribute(TicketConstant.SESSION_KEY.TLS_MEM_NO) String memNo,
			ModelMap model) {
		paramVo.setMemNo(memNo);
		paramVo.getPage().setPageSize("500");
		String inputString = JSON.toJSONString(paramVo, true);
		LOG.info("导出运单输入参数：" + inputString);
		List<OrderExportDataVo> dataVos = null;
		try {
			String jsonString = orderService.vagueMemBillOrder(inputString);
			UCMPResultVo resultVo = JSON.parseObject(jsonString, UCMPResultVo.class);
			JSONObject object = JSONObject.fromObject(resultVo != null ? resultVo.getResult() : null);
			String jArray = object.getString("billList");
			dataVos = JSON.parseArray(jArray, OrderExportDataVo.class);
			String pageString = object.getString("page");
			UCMPPage page = JSON.parseObject(pageString, UCMPPage.class);
			LOG.info("UCMP返回的运单分页数据：" + JSON.toJSONString(page, true));
			int totalPage = page.getTotalPage();
			if (totalPage > 1) {
				for (int i = 2; i <= totalPage; i++) {
					paramVo.getPage().setCurrentPage(String.valueOf(i));
					String ret = orderService.vagueMemBillOrder(JSON.toJSONString(paramVo));
					UCMPResultVo uVo = JSON.parseObject(ret, UCMPResultVo.class);
					JSONObject jResult = JSONObject.fromObject(uVo != null ? uVo.getResult() : null);
					String orderArray = jResult.getString("billList");
					List<OrderExportDataVo> dataList = JSON.parseArray(orderArray, OrderExportDataVo.class);
					if (dataList != null) {
						dataVos = ListUtils.union(dataVos, dataList);
					}
				}
			}
			model.put("orderList", dataVos);
		} catch (Exception e) {
			LOG.error("导出运单异常：", e);
		}
		return new ModelAndView(new OrderExportExcelView(), model);
	}

	/**
	 * 运送中的的运单信息:做了50的运单
	 * 
	 * @version ISNV2.0
	 * @author sfit0168 by 2015-7-22
	 */
	@RequestMapping(value = "/new/waybill/route", method = RequestMethod.GET)
	@ResponseBody
	public List<WaybillNewVO> queryWaybillRouteInfo(String bnos) throws UnsupportedEncodingException {
		// 根据memno获取客户的所有的运单信息
		return wayBillNewService.getRouteInfo(bnos);
	}

	/**
	 * 修改快件信息
	 */
	@RequestMapping(value = "/waybill/modify/nottakepart", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo modifyExpressDelivery(@RequestParam("orderList") String orderList, HttpSession session) {
		long start = System.currentTimeMillis();
		JSONArray jsonArray = JSONArray.fromObject(orderList);
		OrderRecVo orderRecVo = getOrderVoList(jsonArray);
		// 未打印的直接修改原信息的信息;有打印的重新生成运单号并且关联新的运单号信息
		ResultVo result = checkOrder(orderRecVo);
		if ("1".equals(result.getStatus())) {
			// 将订单信息放入缓存
			OrderRecVo orderRec = (OrderRecVo) session.getAttribute(SystemContants.SessionKey.MODIFY_ORDER_RECEIVER);
			if (orderRec != null) {
				session.removeAttribute(SystemContants.SessionKey.MODIFY_ORDER_RECEIVER);
			}
			session.setAttribute(SystemContants.SessionKey.MODIFY_ORDER_RECEIVER, orderRecVo);
		}
		long end = System.currentTimeMillis();
		String string = LoggerByLevel.kLogMsgV1Success("modifyExpressDelivery", (end - start));
		LoggerByLevel.INFO_LOGGER.info(string);
		return result;
	}

	private OrderRecVo getOrderVoList(JSONArray jsonArray) {
		Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
		// classMap.put("orderRecList", OrderRecVo.class);
		// classMap.put("addiServceVo", OrderAddiServiceVo.class);
		classMap.put("orderRecAddr", OrderRecAddressVo.class);
		classMap.put("orderSendAddr", OrderSenderVo.class);
		classMap.put("addiServceVo", OrderRecPropsVo.class);
		return (OrderRecVo) JSONObject.toBean(jsonArray.getJSONObject(0), OrderRecVo.class, classMap);
	}

	/**
	 * 未取件的运单信息:1、没有生成运单号的订单信息；2、有生成运单但没有取件的
	 * 
	 * @version ISNV2.0
	 * @author sfit0168 by 2015-7-22
	 */
	@RequestMapping(value = "/waybill/nottakepart", method = RequestMethod.POST)
	@ResponseBody
	public Page<WaybillNewVO> queryNotTakePart(String waybillno, String company, String name, String telephone, String startTm,
			String endTm, String address, Page<WaybillNewVO> page, HttpSession httpSession) throws UnsupportedEncodingException {
		long start = System.currentTimeMillis();
		// 获取用户的memno
		String memno = UserSession.getMemNo();
		if (null == memno || "".equals(memno)) {
			// 根据userid获取memno
			memno = wayBillNewService.getMemNobyUserId(UserSession.getUserId());
		}
		String inCompany = company;
		if (company != null && !"".equals(company)) {
			inCompany = URLDecoder.decode(company, UTF_8_ENCODING);
		}
		String inName = name;
		if (name != null && !"".equals(name)) {
			inName = URLDecoder.decode(name, UTF_8_ENCODING);
		}
		String inAddress = address;
		if (address != null && !"".equals(address)) {
			inAddress = URLDecoder.decode(address, UTF_8_ENCODING);
		}
		Page<WaybillNewVO> waybillPage = wayBillNewService.getWaybillByMemno(memno, waybillno, inCompany, inName, telephone, startTm, endTm,
				inAddress, page);
		long end = System.currentTimeMillis();
		String string = LoggerByLevel.kLogMsgV1Success("queryNotTakePart", (end - start));
		LoggerByLevel.INFO_LOGGER.info(string);
		return waybillPage;
	}

	/**
	 * 修改快件信息，点击消单、催单按钮(表示取消订单)
	 */
	@RequestMapping(value = "/waybill/nottakepart/{action}", method = RequestMethod.POST)
	@ResponseBody
	public Object cancelExpressDelivery(@RequestParam("orderNo") String orderNo, @RequestParam("waybillNo") String waybillNo,
			@RequestParam("recAddressId") String recAddressId, @PathVariable("action") String action, HttpSession session,
			String cancelOrderReason) {
		long start = System.currentTimeMillis();
		String langCode = getUserLangCode();
		String memno = UserSession.getMemNo();
		OrderVo ordersVo = new OrderVo();
		ordersVo.setUserId(memno);
		ordersVo.setAction(action);
		ordersVo.setOrderNo(orderNo);
		ordersVo.setCancelOrderReason(cancelOrderReason);
		// ===SFIT0033===从session获取LangCode
		ordersVo.setLangCode(langCode);
		UpdateOrdersVO result = myOrderNewService.updateMyOrders(ordersVo, "1");
		long end = System.currentTimeMillis();
		String string = LoggerByLevel.kLogMsgV1Success("cancelExpressDelivery", (end - start));
		LoggerByLevel.INFO_LOGGER.info(string);
		if ("URGE".equals(action)) {
			return JSON.parseObject(result.getErrorcode(), ResultUCMPVo.class);
		}
		return result;
	}

	/**
	 * 批量取消待取件
	 * 
	 * @return
	 */
	@RequestMapping(value = "/waybillDetail/deleteNottakeparts", method = RequestMethod.POST)
	@ResponseBody
	public void deleteNottakeparts(@RequestParam("waybillNos") String waybillNos, @RequestParam("orderNos") String orderNos) {
		LOG.info("批量取消待取件--waybillNos:(" + waybillNos + ")" + "--" + "orderNos:(" + waybillNos + ")");
		long start = System.currentTimeMillis();
		String langCode = getUserLangCode();
		String userId = UserSession.getMemNo();
		for (String waybillNo : waybillNos.split(",")) {
			OrderVo ordersVo = new OrderVo();
			ordersVo.setUserId(userId);
			ordersVo.setOrderNo(waybillNo);
			ordersVo.setAction("CANCEL");
			ordersVo.setCancelOrderReason("待取件批量取消");
			ordersVo.setLangCode(langCode);
			myOrderNewService.updateMyOrders(ordersVo, "1");
		}
		for (String orderNo : orderNos.split(",")) {
			OrderVo ordersVo = new OrderVo();
			ordersVo.setUserId(userId);
			ordersVo.setOrderNo(orderNo);
			ordersVo.setAction("CANCEL");
			ordersVo.setCancelOrderReason("待取件批量取消");
			ordersVo.setLangCode(langCode);
			myOrderNewService.updateMyOrders(ordersVo, "1");
		}

		long end = System.currentTimeMillis();
		String string = LoggerByLevel.kLogMsgV1Success("deleteNottakeparts", (end - start));
		LoggerByLevel.INFO_LOGGER.info(string);

	}

	/**
	 * 修改快件信息，点击打印按钮
	 */
	@RequestMapping(value = "modity/waybill/modify/nottakepart", method = RequestMethod.GET)
	@ResponseBody
	public ResultVo printModifyExpressDelivery(HttpSession session) {
		// 清楚缓存中的
		OrderRecVo orderRecVo = (OrderRecVo) session.getAttribute(SystemContants.SessionKey.MODIFY_ORDER_RECEIVER);
		orderRecVo.setMemNo(UserSession.getMemNo());
		return wayBillNewService.updateExpress(orderRecVo);
	}

	private ResultVo checkOrder(OrderRecVo orderRecVo) {
		if (orderRecVo == null || StringUtils.isEmpty(orderRecVo.getRecAddressId())) {
			return ResultVo.error(SystemContants.ErrorCode.EXPRESS_RECADDRESS_ERROR, "快件收件信息错误");
		}
		if (StringUtils.isEmpty(orderRecVo.getOrderNo())) {
			return ResultVo.error(SystemContants.ErrorCode.EXPRESS_ORDER_NULL, "快件收件信息错误");
		}
		// 验证收件人是否为空
		if (StringUtils.isEmpty(orderRecVo.getOrderRecAddr().getContactName())
				|| BlackKeywordInterceptor.isUnsafe(orderRecVo.getOrderRecAddr().getContactName())) {
			return ResultVo.error(SystemContants.ErrorCode.EXPRESS_CONTACTNAME_ERROR, "快件收件姓名错误");
		}

		// 判断手机和固话的规则
		if (StringUtils.isEmpty(orderRecVo.getOrderRecAddr().getContactPhone())
				&& StringUtils.isEmpty(orderRecVo.getOrderRecAddr().getContactMobile())) {
			return ResultVo.error(SystemContants.ErrorCode.EXPRESS_CONTACT_ERROR, "收件手机和固话都为空");
		}

		// 托寄物内容 30字符
		if (StringUtils.isEmpty(orderRecVo.getOrderRecProps().getCargoName())
				|| this.getStringLengthForDBType(orderRecVo.getOrderRecProps().getCargoName()) > 100
				|| BlackKeywordInterceptor.isUnsafe(orderRecVo.getOrderRecProps().getCargoName())) {
			return ResultVo.error(SystemContants.ErrorCode.EXPRESS_CONTACTCARGONAME_ERROR, "快件托寄物错误");
		}

		// 付款方式选择寄付月结、寄付转第三方付，月结卡号为空的 PaymentType
		if ((SystemContants.PaymentType.THIRD_PAYMENT.equals(orderRecVo.getOrderRecProps().getPayType())
				|| SystemContants.PaymentType.FOUR_PAYMENT.equals(orderRecVo.getOrderRecProps().getPayType()))
				&& (StringUtils.isEmpty(orderRecVo.getOrderRecProps().getCardNo()))) {
			return ResultVo.error(SystemContants.ErrorCode.EXPRESS_CONTACTCARDNO_ERROR, "快件月结或者第三方付,但月结卡号为空");
		}
		if (StringUtils.isNotEmpty(orderRecVo.getOrderRecAddr().getContactMobile())
				&& !Common.isNewContactPhone(orderRecVo.getOrderRecAddr().getContactMobile())) {
			return ResultVo.error(SystemContants.ErrorCode.MOBILE_REGION_CONFLICT, "联系方式手机不匹配");
		}
		if (StringUtils.isNotEmpty(orderRecVo.getOrderRecAddr().getContactPhone())
				&& !Common.isNewContactPhone(orderRecVo.getOrderRecAddr().getContactPhone())) {
			return ResultVo.error(SystemContants.ErrorCode.MOBILE_REGION_CONFLICT, "联系方式固话不匹配");
		}

		// 大闸蟹
		String validCrabRecInfo = validCrabRecInfo(orderRecVo.getOrderRecProps().getPayType(), orderRecVo.getOrderRecProps().getProdType(),
				orderRecVo.getOrderRecAddr().getProviceCode());
		if (!SUCCESS.equals(validCrabRecInfo)) {
			return ResultVo.error(SystemContants.ErrorCode.EXPRESS_PROD_ERROR, "该省不支持大闸蟹或者付款方式错误");
		}

		// 效验产品类型
		Map<String, String> params = new HashMap<String, String>();
		params.put("prodType", orderRecVo.getOrderRecProps().getProdType());
		params.put("sCountyCode", orderRecVo.getOrderSendAddr().getCountyCode());
		params.put("sCityCode", orderRecVo.getOrderSendAddr().getCityCode());
		params.put("rCityCode", orderRecVo.getOrderRecAddr().getCityCode());
		params.put("sProviceName", orderRecVo.getOrderSendAddr().getProviceName());
		params.put("sCityName", orderRecVo.getOrderSendAddr().getCityName());
		params.put("sCountyName", orderRecVo.getOrderSendAddr().getCountyName());
		params.put("rProviceName", orderRecVo.getOrderRecAddr().getProviceName());
		params.put("rCityName", orderRecVo.getOrderRecAddr().getCityName());
		params.put("rCountyName", orderRecVo.getOrderRecAddr().getCountyName());
		params.put("isBooking", orderRecVo.getOrderRecProps().getIsBooking());
		params.put("appointTime", orderRecVo.getOrderRecProps().getBookingTime());
		params.put("weight", StringUtils.toStr(orderRecVo.getOrderRecProps().getWeight()));
		params.put("payType", StringUtils.toStr(orderRecVo.getOrderRecProps().getPayType()));
		params.put("isVerifyTime", !"0".equals(orderRecVo.getOrderRecProps().getIsSelfSend())
				/*
				 * || "1".equals(orderRecVo.getOrderRecProps().getIsBooking())
				 */ ? "0" : "1");// 自寄件/预约都不需效验截单时间
		ResultVo rv = orderNewService.checkProdIsAvailableSec(params);
		if ("1".equals(rv.getStatus())) {
			if ("T104".equals(StringUtils.toStr(rv.getResult()))) {
				orderRecVo.getOrderRecProps().setProdType(StringUtils.toStr(rv.getResult()));
			}
		} else {
			return rv;
		}
		return ResultVo.success("success");
	}

	private String validCrabRecInfo(String payType, String prodType, String proviceCode) {
		List<String> noneCrabsProIdList = Arrays.asList(orderService.getNoneCrabsProlist().split(","));
		if ((SystemContants.CRAB_PROD_TYPE_VALUE.equals(prodType) || SystemContants.FISH_PROD_TYPE_VALUE.equals(prodType))
				&& noneCrabsProIdList.contains(proviceCode)) {
			return SystemContants.CRAB_NONE_PRI_PRO;
		}
		if ((SystemContants.CRAB_PROD_TYPE_VALUE.equals(prodType) || SystemContants.FISH_PROD_TYPE_VALUE.equals(prodType))
				&& SystemContants.PaymentType.REC_PAYMENT.equals(payType)) {
			return SystemContants.CRAB_NONE_RECPAY;
		}
		return "success";
	}

	/**
	 * 获取字符串的长度(中文字符占3个字节)
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private int getStringLengthForDBType(String str) {
		try {
			int len = 0;
			if (!StringUtils.isEmpty(str)) {
				for (int i = 0; i < str.length(); i++) {
					if (String.valueOf(str.charAt(i)).getBytes("GBK").length == 1) {
						len += 1;
					} else {
						len += 3;
					}
				}
			}
			return len;
		} catch (UnsupportedEncodingException e) {
			LOG.error(e);
			return 0;
		}
	}

	private String getUserLangCode() {
		UserLocaleInfo userLocaleInfo = UserSession.getUserLocaleInfo();
		// 获取用户语言信息
		String langCode = "zh-cn";
		if (userLocaleInfo != null) {
			String langCodeOfUser = userLocaleInfo.getLangCode();
			if ("en".equalsIgnoreCase(langCodeOfUser)) {
				langCode = "en";
			} else if ("tc".equalsIgnoreCase(langCodeOfUser)) {
				langCode = "zh-tw";
			}
		}
		return langCode;
	}

	/**
	 * 调用UCMP接口-查询运单列表数据
	 * 
	 * @param status
	 * @param page
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/new/waybill/queryUcmp/{status}", method = RequestMethod.POST)
	@ResponseBody
	public Page<WaybillNewVO> queryUCMPWayBillList(@PathVariable("status") String status, Page<WaybillNewVO> page,
			HttpServletRequest request) {
		Page<WaybillNewVO> wayBillNewPage = new Page<WaybillNewVO>();
		long startTimeMS = System.currentTimeMillis();
		if (StringUtils.isEmpty(status) || page == null) {
			return wayBillNewPage;
		}
		String type = request.getParameter("type"); // 查询类型（0所有、1我寄出的、2寄给我的）
		String name = request.getParameter("name");
		String company = request.getParameter("company");
		String phone = request.getParameter("telephone");
		String address = request.getParameter("address");
		String startTm = request.getParameter("startTm");
		String endTm = request.getParameter("endTm");
		String waybillno = request.getParameter("waybillno"); // 运单号
		try {
			if (StringUtils.isNotEmpty(company)) {
				company = URLDecoder.decode(company, UTF_8_ENCODING);
			}
			if (StringUtils.isNotEmpty(name)) {
				name = URLDecoder.decode(name, UTF_8_ENCODING);
			}
			if (StringUtils.isNotEmpty(address)) {
				address = URLDecoder.decode(address, UTF_8_ENCODING);
			}
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("countryCode", UserSession.getUserLocaleInfo().getCountryCode());
			paramMap.put("langCode", UserSession.getUserLocaleInfo().getLangCode());
			paramMap.put("mediaCode", "PC.MEMBER");
			paramMap.put("systemCode", "PC.MEMBER");
			paramMap.put(MEM_NO, UserSession.getMemNo());
			paramMap.put("page", page);
			paramMap.put("status", status);
			paramMap.put("type", type);
			paramMap.put("name", name);
			paramMap.put("company", company);
			paramMap.put("phone", phone);
			paramMap.put("address", address);
			paramMap.put("startTm", startTm);
			paramMap.put("endTm", endTm);
			paramMap.put("bno", waybillno);

			wayBillNewPage = wayBillNewService.getUCMPWaybillInfo(paramMap);

			if (("signed".equals(status) || "all".equals(status)) && wayBillNewPage != null && wayBillNewPage.getResult() != null) {
				List<String> signedBnos = new ArrayList<String>();
				for (WaybillNewVO waybillNewVO : wayBillNewPage.getResult()) {
					signedBnos.add(waybillNewVO.getWaybillno());
				}
				request.getSession().setAttribute("signedBnos", signedBnos);
			}
		} catch (Exception e) {
			LOG.error("queryUCMPWayBillList failed: ", e);
		} finally {
			String ip = WebServiceUtil.getUserIpAddr(request);
			long endTimeMS = System.currentTimeMillis();
			// String string =
			// LoggerByLevel.kLogMsgV1Success("queryUCMPWayBillForList",
			// (endTimeMS - startTimeMS));
			// LoggerByLevel.INFO_LOGGER.info(string);
			LOG.info(ip + "|waybillno:" + waybillno + "|type:" + type + "|company:" + company + "|name:" + name + "|telephone:" + phone
					+ "|startTm:" + startTm + "|endTm:" + endTm + "|address:" + address + "|costTimeMS:" + (endTimeMS - startTimeMS));
		}
		return wayBillNewPage;
	}

	/**
	 * 调用UCMP查询最新预计送达时间
	 * 
	 * @param bnos
	 *            多个订单号 ,分割
	 * @return
	 */
	@RequestMapping(value = "/new/waybill/queryUcmp/expectedDeliveryTm", method = RequestMethod.POST)
	@ResponseBody
	public String queryTime(String bnos) {
		List<WaybillNewVO> waybills = wayBillNewService.getRouteInfo(bnos);
		JSONArray array = new JSONArray();
		for (WaybillNewVO waybill : waybills) {
			JSONObject obj = new JSONObject();
			obj.element("bno", waybill.getWaybillno());
			obj.element("initExpectedDeliveryTm", waybill.getInitExpectedDeliveryTm());
			obj.element("lastExpectedDeliveryTm", waybill.getLastExpectedDeliveryTm());
			// 新接口字段
			obj.element("isDelay", waybill.getIsDelay());
			obj.element("dynamicExpectedDeliveryTm", waybill.getDynamicExpectedDeliveryTm());
			obj.element("expectedDeliveryTm", waybill.getExpectedDeliveryTm());
			array.add(obj);
		}
		return array.toString();
	}

	/**
	 * 单票件修改
	 * 
	 * @param orderList
	 * @param areaCode
	 * @param lanCode
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/{areaCode}/{lanCode}/waybill/singlemod", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo singleOrderMod(@RequestParam("orderList") String orderList, @PathVariable("areaCode") String areaCode,
			@PathVariable("lanCode") String lanCode, HttpServletRequest request) {
		String reqIp = WebServiceUtil.getUserIpAddr(request);
		String memNo = UserSession.getMemNo();
		LOG.info("单票件改单参数{reqIp:" + reqIp + "|memNo:" + memNo + "reqData:" + orderList + "}");

		try {
			return orderServiceHandler.modSingleOrder(orderList, areaCode, lanCode);
		} catch (Exception e) {
			LOG.error("modSingleOrder check error:", e);
		}
		return ResultVo.error(SystemContants.ErrorCode.EXCEPTION, "系统异常");
	}

	/**
	 * 对巴枪做了3/5/6等异常收件操作的订单进行回复
	 * 
	 * @param params
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/waybillDetail/replysfer", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo replysfer(String params, HttpServletRequest request) {
		try {
			String memNo = UserSession.getMemNo();
			if (StringUtils.isEmpty(memNo) || StringUtils.isEmpty(params)) {
				return ResultVo.error(SystemContants.ErrorCode.PARAM_NULL, PARAM_NULL);
			}
			JSONObject jo = JSONObject.fromObject(params);
			Map<String, Object> map = new HashMap<String, Object>();
			Map<String, Object> addr = new HashMap<String, Object>();
			addr.put("provinceCode", jo.getString("provinceId"));
			addr.put("provinceName", jo.getString("provinceName"));
			addr.put("cityCode", jo.getString("cityId"));
			addr.put("cityName", jo.getString("cityName"));
			addr.put("countyCode", jo.getString("areaId"));
			addr.put("countyName", jo.getString("areaName"));
			addr.put("address", jo.getString("detailAddr"));

			map.put("id", jo.getString("msgId"));
			map.put("contact", jo.getString("contact"));
			map.put(MEM_NO, memNo);
			map.put("orderNo", jo.getString("orderNo"));
			map.put("reasonCode", jo.getString("reasonCode"));
			map.put("addr", addr);
			ResultVo ret = orderNewService.replysfer(map);
			LOG.info("异常件回复收派员replysfer由dcn返回结果：" + ret);
			return ret;
		} catch (Exception e) {
			LOG.error("异常件回复replysfer出错", e);
		}
		return ResultVo.error("syserr", "系统异常");
	}

	/**
	 * 根据订单和消息ID查询用户订单是否做了3/5/6等异常操作
	 * 
	 * @param orders
	 * @return
	 */
	@RequestMapping(value = "/waybillDetail/queryreplysfer", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo queryreplysfer(String orders) {
		String memNo = UserSession.getMemNo();
		if (StringUtils.isEmpty(orders) || StringUtils.isEmpty(memNo)) {
			return ResultVo.error(PARAM_NULL, "参数为空");
		}
		try {
			JSONArray ja = JSONArray.fromObject(orders);
			if (ja == null || ja.isEmpty()) {
				return ResultVo.error(PARAM_NULL, "参数为空");
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("orders", ja);
			map.put(MEM_NO, memNo);
			return orderNewService.queryReplysfer(map);
		} catch (Exception e) {
			LOG.error("查询异常消息queryreplysfer报错", e);
		}
		return ResultVo.error("fail", "查询出错");
	}

	/**
	 * 运单导出进度
	 * 
	 * @return
	 */
	@RequestMapping(value = "/waybillExport/percent", method = RequestMethod.GET)
	@ResponseBody
	public Object getPercent() {
		Object percent = UserSession.getSession(SystemContants.ORDER_EXPORT_PERCENT);
		if (percent != null && NumberUtils.isNumber(percent.toString())) {
			Integer p = Integer.valueOf(percent.toString());
			if (p >= 100) {
				p = 100;
				UserSession.setSession(SystemContants.ORDER_EXPORT_PERCENT, "0");
			}
			return p;
		}
		return 0;
	}
}
